// 数据缓存管理
import {req} from '@/components/service/index'
import reqDirstribute from './req_mdl_conf'
import loop from '@/utils/loop.js'

//modules
import mainStore from './main/index'
import carTableStore from './car_table/index'
import carFromStore from './car_form/index'
import organization from './organization/index'
import modConf from './mod_conf/index'
import auditing from './auditing/index'
import localStore from './local/index'

// 创建模块
function creatModel (mod:any):any{
    return {
        namespaced: true,
        ...(new mod())
    }
}

class store_index_config{

    modules = {

        mainStore: creatModel(mainStore),
        carTableStore: creatModel(carTableStore),
        carFormStore: creatModel(carFromStore),
        organizationStore: creatModel(organization),
        modConf: creatModel(modConf), 
        auditingStore: creatModel(auditing),
        localStore: creatModel(localStore),
    }

    state = {
        
    }

    mutations = {
        // 空函数
        empty(){}
    }

    getters = {

    }
    
    // 数据请求分发
    actions = {


        /*
        ** 调用数据请求/发送接口  params: { url: 调用方法关键字, data:请求数据 }
        ** @params
                ps: 请求参数
        */
        request ({commit, state, dispatch}, ps:commonInf.params){
            const path = ps.url;
            
            return req(ps).then(data =>{

                const conf = reqDirstribute[path];
                let {reqSuccess, resData} = data;

                
                /*
                ** 创建请求状态
                ** reqStatus:boolean = statusCode === 200;               
                */
                if(reqSuccess){

                    // 报错
                    if(!conf){
                        throw `数据分发配置不存在: ${path}`
                    }

                    // 路由
                    conf.forEach(item =>{

                        let { propPath, commit:cit, action:act } = item;
                        let pushData = propPath === '*' ? resData : loop.addressing(resData, propPath);

                        // 区分分发类型
                        if(cit){
                            commit(cit, pushData);
                        }

                        if(act){
                            dispatch(act, pushData);
                        }

                     
                    })
                    
                }

                return reqSuccess;

            })
        }  
        
    }


    
    
}

export default store_index_config
